﻿using System.Collections.Generic;
using System.Threading.Tasks;


namespace Abp.Authorization
{
    using System;

    using Skymate;
    using Skymate.Authorization;
    using Skymate.Authorization.Attributes;
    using Skymate.Engines;
    using Skymate.Extensions;
    using Skymate.Threading;

    internal class AuthorizeAttributeHelper : IAuthorizeAttributeHelper, ITransientDependency
    {
        public IWorkContext WorkContext { get;private set; }

        public IPermissionChecker PermissionChecker { get; set; }

        /*public IAbpSession AbpSession { get; set; }

        
*/
        public AuthorizeAttributeHelper()
        {
            WorkContext = EngineContext.Current.Resolve<IWorkContext>();

            PermissionChecker = EngineContext.Current.Resolve<IPermissionChecker>();

            /*AbpSession = NullAbpSession.Instance;
            PermissionChecker = NullPermissionChecker.Instance;*/
        }

        public async Task AuthorizeAsync(IEnumerable<IAbpAuthorizeAttribute> authorizeAttributes)
        {
            if (this.WorkContext.CurrentCustomer.IsNullOrEmpty())
            {
                throw new AbpAuthorizationException("no user is logined");
            }


            // IsGranted

/*
            foreach (var authorizeAttribute in authorizeAttributes)
            {
                await
                    PermissionChecker.AuthorizeAsync(
                        Guid.Parse(this.WorkContext.CurrentCustomer),
                        authorizeAttribute.Permissions);
                // PermissionChecker.AuthorizeAsync(authorizeAttribute.RequireAllPermissions, authorizeAttribute.Permissions);
            }*/

            /* if (!AbpSession.UserId.HasValue)
             {

             }

             */
        }

        public async Task AuthorizeAsync(IAbpAuthorizeAttribute authorizeAttribute)
        {
            await AuthorizeAsync(new[] { authorizeAttribute });
        }

        public void Authorize(IEnumerable<IAbpAuthorizeAttribute> authorizeAttributes)
        {
            AsyncHelper.RunSync(() => AuthorizeAsync(authorizeAttributes));
        }

        public void Authorize(IAbpAuthorizeAttribute authorizeAttribute)
        {
            Authorize(new[] { authorizeAttribute });
        }
    }
}